<?php 

require_once("role_functions.php");

extract($_POST);
extract($_GET);

$title = "Role Comparison Tool";

$outypes = array('Organization','Course Template','Course Offering','Group','Semester','Section','Department','Academic Type','Faculty','Mode');

//
// Get the roles to compare
if(isset($leftRole)) {
	list($leftRole, $leftSite) = explode('|',$leftRole);
} else {
	$leftRole = "Administrator";
	$leftSite = "Prod";
}
if(isset($rightRole)) {
	list($rightRole, $rightSite) = explode('|',$rightRole);
} else {
	$rightRole = "Course Manager";
	$rightSite = "Prod";
}
if (!isset($outype)) {
	$outype = "All";
}
if (!isset($allvals)) {
	$allvals = "All";
}
if (!isset($site)) {
	$site = "Prod";
}
if (!isset($tool)) {
	$tool = "Accelerator";
}

//
// Open Database connection
$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
    die('Could not connect: ' . mysql_error());
} else {
  $rolesettings = mysql_select_db("RoleSettings", $link);
  
  if (!$rolesettings) {
      die ('Can\'t use foo : ' . mysql_error());
  } 
}

$thesearch = "";

//
// What to query
if(isset($reaction)) {
	switch($reaction) {
		case"comparekeyroles":
			$thesearch = '<h4>Compare key roles on '.$site.'.</h4>';
			$display = "comparekeyroles";			
			break;
		case"proddev":
			$thesearch = '<h4>Comparing all roles 1 to 1 between Prod and Dev across all OUtypes, showing differences only.</h4>';
			$display = "proddev";			
			break;
		case"nocompare":
			$thesearch = '<h4>Plain, single list of each role on '.$site.'.</h4>';
			$display = "nocompare";			
			break;
		case"prodtest":
			$thesearch = "<h4>Comparing all roles 1 to 1 between Prod and Test across all OUtypes, showing differences only.</h4>";
			$display = "prodtest";
			break;
		case"bigcompare":
			$title = "All Roles";
			$display = "bigcompare";
			$thesearch = "<h4>Comparing ".$allvals." for <b>All</b> roles on ".$site." where OU is ".$outype."</h4>";
			break;
		case"toolcompare":
			$title = "Viewing one tool across roles on ".$site;
			$display = "toolcompare";
			$thesearch = "<h4>".$title."</h4>";
			break;
		case"alltools":
			$title = "Viewing all tools across roles on ".$site;
			$display = "alltools";
			$thesearch = "<h4>".$title."</h4>";
			break;
		case"compare":
			$title = $leftRole." on ".$leftSite." vs. ".$rightRole." on ".$rightSite;
			$display = "compare";
			$thesearch = "<h4>Comparing ".$allvals." for ".$leftRole." on ".$leftSite." against ".$rightRole." on ".$rightSite. " where OrgUnit scope is ".$outype."</h4>";
			break;
		default:
			$display = "Empty";
			break;
	} // end switch
} else {
	$reaction = "";
}//end if

$thesearch .= '<button class="actions" id="loading" onclick="cancelpage();"> Loading... click to cancel</button>';
flush();

//
// Build Dropdowns
$sql = "SELECT DISTINCT `Tool` FROM `Roles` ORDER BY `Key`";
$result = mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $sql;
    die($message);
}
$toolOptions = "";

$i = 1;
while ($row = mysql_fetch_assoc($result)) {
	$toolOptions .= '<option value="'.$row['Tool'].'">'.$row['Tool'].'</option>'."\n";
}

//
// Build Dropdowns
$sql = "SELECT * FROM `SystemRoles` ORDER BY `system`, `order`";
$result = mysql_query($sql);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $sql;
    die($message);
}
$options = "";
$prod_roles = "";
$test_roles = "";
$dev_roles = "";
$prodtestlist = "";
$roleReference = array();

$i = 1;

while ($row = mysql_fetch_assoc($result)) {
	$options .= '<option value="'.$row['roleName'].'|'.$row['system'].'">'.$i++.'. '.$row['roleName'].' on '.$row['system'].'</option>'."\n";
	
	if($row['system'] == "Prod") {
		$short = preg_replace('/\s+/','',$row["roleName"]);
		$roleReference[] = $row["roleName"];
		$prodtestlist .= '<a class="toc'.$short.' href="#'.preg_replace('/\s+/','',$row["roleName"].$row["roleName"]).'">'.$row["roleName"].'</a><BR>';
		
		$prod_roles .= '<li><a class="prodRole" name="prodRole'.$row['roleId'].'" target="_blank" onclick="popup(this.name,\'\',\''.$row['roleId'].'\');return false;" href="#">'.$row['roleName'].'</a></li>'."\n";
	} else if($row['system'] == "Test") {
		$test_roles .= '<li><a class="testRole" name="testRole'.$row['roleId'].'" target="_blank" onclick="popup(this.name,\'test\',\''.$row['roleId'].'\');return false;" href="#">'.$row['roleName'].'</a></li>'."\n";
	
	} else {
		$dev_roles .= '<li><a class="devRole" name="devRole'.$row['roleId'].'" target="_blank" onclick="popup(this.name,\'dev\',\''.$row['roleId'].'\');return false;" href="#">'.$row['roleName'].'</a></li>'."\n";
	}
}


mysql_free_result($result);



?>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="print.css" media="print">
  <link rel="stylesheet" type="text/css" href="screen.css">

  <script type="text/javascript" src="jquery-132min.js"></script>
  <script type="text/javascript" src="roles.js"></script>
<script type="text/javascript">
//
// Adjust all the Select lists to the currently selected option
function preset() {
  	//
  	//  Setup the previous selected <option>
  	$('select[name="leftRole"] option[value="<? echo $leftRole."|".$leftSite; ?>"]').attr("selected", true);
  	$('select[name="rightRole"] option[value="<? echo $rightRole."|".$rightSite; ?>"]').attr("selected", true);  
  	$('select[name="outype"] option[value="<? echo $outype; ?>"]').attr("selected", true);  
  	$('select[name="allvals"] option[value="<? echo $allvals; ?>"]').attr("selected", true);  
  	$('select[name="reaction"] option[value="<? echo $reaction; ?>"]').attr("selected", true);  
  	$('select[name="site"] option[value="<? echo $site; ?>"]').attr("selected", true);  
  	$('select[name="tool"] option[value="<? echo $tool; ?>"]').attr("selected", true);  
	checkReaction();
		
	//
	// Hover effect.
	$('table.compareTable tbody tr').hover(function(){  
		  $(this).find('td').addClass('hovered');  
	}, function(){  
		  $(this).find('td').removeClass('hovered');  
	});
			
	//default each row to visible
	$('table.compareTable tbody tr').addClass('visible');

	//overrides CSS display:none property
	//so only users w/ JS will see the
	//filter box
	$('#search').show();

	$('.filter').keyup(function(event) {
		var tableName = $(this).attr("name");
		tableName = 'table[name="t'+tableName.substr(1,tableName.length)+'"]';
		//if esc is pressed or nothing is entered
		if (event.keyCode == 27 || $(this).val() == '') {
			//if esc is pressed we want to clear the value of search box
			$(this).val('');

			//we want each row to be visible because if nothing
			//is entered then all rows are matched.
		    $(tableName +' tbody tr').removeClass('visible').show().addClass('visible');
		} else { //if there is text, lets filter
		      filter(tableName +' tbody tr', $(this).val());
		}
	});	
	
	//grab all header rows  
    $('table.compareTable thead th').each(function(column) {  
      $(this).addClass('sortable').click(function(){  
        var findSortKey = function($cell) {  
          return $cell.find('.sort-key').text().toUpperCase() + ' ' + $cell.text().toUpperCase();  
        };  
        var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;  

        //step back up the tree and get the rows with data  
        //for sorting  
        var $rows = $(this).parent().parent().parent().find('tbody tr').get();  

        //loop through all the rows and find  
        $.each($rows, function(index, row) {  
          row.sortKey = findSortKey($(row).children('td').eq(column));  
        });  

        //compare and sort the rows alphabetically  
        $rows.sort(function(a, b) {  
            if (a.sortKey < b.sortKey) return -sortDirection;  
            if (a.sortKey > b.sortKey) return sortDirection;  
            return 0;  
        });  

        //add the rows in the correct order to the bottom of the table  
        $.each($rows, function(index, row) {  
            $('table.compareTable tbody').append(row);  
            row.sortKey = null;  
        });  

        //identify the column sort order  
        $('th').removeClass('sorted-asc sorted-desc');  
        var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');  
        sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');  

        //identify the column to be sorted by  
        $('td').removeClass('sorted')  
                    .filter(':nth-child(' + (column + 1) + ')')  
                    .addClass('sorted');  

      });  
    });  
	
	$("#loading").html("<b>Loaded</b>");
	$('#searchForm').css('visibility','visible');
	toggleEmptyTables();
}

</script>

<title><? echo $title; ?></title>
</head>

<body onload="preset();">
<div class="actions" name="top">
<form action="roles.php" method="post" id="searchForm" style="visibility:hidden">
<table>
<tr>
	<td>
		Action: <select name="reaction" id="reaction" onChange="checkReaction();">
        	<option value="comparekeyroles">Compare Key Roles</option>  
        	<option value="compare">Compare Two</option>  
        	<option value="bigcompare">Compare All</option>  
        	<option value="prodtest">Compare Prod vs. Test</option>  
        	<option value="proddev">Compare Prod vs. Dev</option>  
        	<option value="nocompare">View Single Roles</option>  
        	<option value="toolcompare">Compare One Tool</option>  
        	<option value="alltools">All Tools</option>  
        </select>
	</td>
	<td name="tdsite">
		System: <select name="site">
        	<option value="Prod">Prod</option>  
        	<option value="Test">Test</option>  
        	<option value="Dev">Dev</option>  
        </select>
	</td>
	<td name="tdleft">
		Compare: <select name="leftRole">
			<? echo $options; ?>
        </select>
	</td>
	<td name="tdright">
		Against: <select name="rightRole">
			<? echo $options; ?> 
        </select>
	</td>
	<td name="tdtool">
		Tool: <select name="tool">
			<? echo $toolOptions; ?> 
        </select>
	</td>
    <td name="tdscope">
		OU Scope: <select name="outype">
        	<option value="All">All</option>  
        	<option value="Organization">Organization</option>  
        	<option value="Course Template">Course Template</option>  
        	<option value="Course Offering">Course Offering</option>  
        	<option value="Group">Group</option>  
        	<option value="Semester">Semester</option>  
        	<option value="Section">Section</option>  
        	<option value="Department">Department</option>  
        	<option value="Academic Type">Academic Type</option>  
        	<option value="Faculty">Faculty</option>  
        	<option value="Mode">Mode</option>  
    </td>
    <td name="tdshow">
		Show: <select name="allvals">
        	<option value="All">All</option>  
        	<option value="Diffs">Diffs Only</option>  
        	<option value="Ineq">Inequalities</option>  
    </td>
	<td name="tdempties" onChange="toggleEmptyTables();">
		Empty Tables: <select name="empties">
        	<option value="hide">Hide</option>  
        	<option value="show">Show</option>  
        </select>
	</td>

</tr>
<tr><td colspan="9"><br><input type="submit" value="Go"/> </td></tr>
</table>
</form>

</div>
<? 
//
// What to display
if (isset($display)) {
	echo $thesearch;
	
	switch($display) {
		case"nocompare":
			echo '<div class="actions">';
			echo noCompareToc($roleReference);
			echo '</div>'."\n";
			while (list(,$theRole) = each($roleReference)) {
				buildCompareTable("All", "All", $theRole, $leftSite, "None", "None")."<BR>\n";
				flush();
			}
			break;
		case"prodtest":
			echo '<br><br>'.$prodtestlist."<BR>\n";
			while (list(,$theRole) = each($roleReference)) {
				buildCompareTable("All", "Diffs", $theRole, "Prod", $theRole, "Test")."<BR>\n";
				flush();
			}
			break;
		case"proddev":
			while (list(,$theRole) = each($roleReference)) {
				buildCompareTable("All", "Diffs", $theRole, "Prod", $theRole, "Dev")."<BR>\n";
				flush();
			}
			break;
		case"bigcompare":
			echo '<div class="actions">'."\n";
			$comparisons = recursive($roleReference, array("TOC"=>""), 0, count($roleReference));
			echo bigCompareToc($comparisons["TOC"]);
			unset($comparisons["TOC"]);
			echo "</div>\n";
			while (list($leftRole, $rightArray) = each($comparisons)) {
				echo '<DIV style="page-break-after:always">'."<h3>".$leftRole."</h3>\n";
				while (list($rightRole, $html) = each($rightArray)) {
					buildCompareTable($outype, $allvals, $leftRole, $site, $rightRole, $site)."<BR>\n";
					flush();
				}
				echo "</DIV>\n";
			}
			
			break;
		case"comparekeyroles":
			echo '<div class="actions">'."\n";
			$comparisons = keyroles($roleReference, array("TOC"=>""), 0, count($roleReference));
			echo bigCompareToc($comparisons["TOC"]);
			unset($comparisons["TOC"]);
			echo "</div>\n";
			while (list($leftRole, $rightArray) = each($comparisons)) {
				echo '<DIV style="page-break-after:always">'."<h3>".$leftRole."</h3>\n";
				while (list($rightRole, $html) = each($rightArray)) {
					buildCompareTable($outype, $allvals, $leftRole, $site, $rightRole, $site)."<BR>\n";
					flush();
				}
				echo "</DIV>\n";
			}

			break;
		case"compare":
			buildCompareTable($outype, $allvals, $leftRole, $leftSite, $rightRole, $rightSite);
			break;
		case"toolcompare":
			buildToolTable($tool, $site, $outypes);
			break; 
		case"alltools":
			buildAllToolsTable($site, $outypes);
			break; 
		default:
			break;
	} // end swtich
	echo "<div><br><i>Produced: ". date('l \t\h\e jS \of F, Y h:i:s A')."</i></div>";
}// endif

?>
<div class="actions">
<h3>Fetch Production Roles [<a href="#" onclick="getProdRoles();">Get ALL</a>]</h3>
<ol>
<? echo $prod_roles; ?>
</ol>
<h3>Fetch Test Roles[<a href="#" onclick="getTestRoles();">Get ALL</a>]</h3>
<ol>
<? echo $test_roles; ?>
</ol>
<h3>Fetch Dev Roles[<a href="#" onclick="getDevRoles();">Get ALL</a>]</h3>
<ol>
<? echo $dev_roles; ?>
</ol>
<a href="build_roles_db.php" target="_blank">Build Database</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="CompareRolesChecklist.xlsx" target="_blank">Compare Roles Checklist (Excel)</a><BR><BR>
</div>

</body>
</html>
<? 
//
// Close DB
mysql_close($link);

?>